package com.leyou.upload.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @author Eric
 * @version v1.0
 * @package com.leyou.upload.service
 * @date 2019/6/25 18:43
 * @description:
 **/
@Service
@Slf4j
public class UploadService {

    private static final String IMAGE_DIR="F:\\javaTool\\nginx-1.12.2\\html\\images";
    private static final String IMAGE_URL="http://image.leyou.com/images/";
    private static final List<String> ALLOW_IMAGE_TYPE= Arrays.asList("image/png", "image/jpeg", "image/bmp","image/jpg");

    public String uploadimage(MultipartFile file) {

        //对file文件校验
        //1.对文件类型进行校验
        String contentType = file.getContentType();
        if (!ALLOW_IMAGE_TYPE.contains(contentType)){
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }

        //2.对文件内容进行校验
        try {
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image==null){
                throw new RuntimeException();
            }
        } catch (Exception e) {
            log.error("文件上传失败，原因是：{}",e.getMessage(),e);
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE,e);
        }

        //文件储存地址
        //1.获取文件名信息
        String filename = file.getOriginalFilename();
        //2.拿到文件的后缀名信息
        String extension = StringUtils.substringAfterLast(filename, ".");
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        filename=uuid+"."+extension;
        File imagePath = new File(IMAGE_DIR, filename);
        //保存文件
        try {
            file.transferTo(imagePath);
        } catch (IOException e) {
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }

        //返回url地址
        return IMAGE_URL+filename;
    }


}
